# 检查数据库连接状态

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "数据库连接诊断工具" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# 1. 检查 .env 配置
Write-Host "1. 检查 .env 配置..." -ForegroundColor Yellow
if (Test-Path .env) {
    $envContent = Get-Content .env
    $dbConfig = $envContent | Where-Object {$_ -like "DB_*"}
    $dbConfig | ForEach-Object { Write-Host "   $_" -ForegroundColor Gray }
}
else {
    Write-Host "   ✗ .env 文件不存在" -ForegroundColor Red
}
Write-Host ""

# 2. 检查 MySQL 服务
Write-Host "2. 检查 MySQL 服务状态..." -ForegroundColor Yellow
try {
    $services = Get-Service -ErrorAction SilentlyContinue | Where-Object {
        $_.Name -like "*mysql*" -or $_.DisplayName -like "*MySQL*"
    }
    
    if ($services) {
        $services | ForEach-Object {
            $color = if ($_.Status -eq 'Running') { 'Green' } else { 'Red' }
            Write-Host "   名称: $($_.Name)" -ForegroundColor $color
            Write-Host "   状态: $($_.Status)" -ForegroundColor $color
        }
    }
    else {
        Write-Host "   ✗ 未找到 MySQL 服务" -ForegroundColor Red
        Write-Host "   提示: MySQL 可能通过 XAMPP/WAMP/Laragon 安装" -ForegroundColor Yellow
    }
}
catch {
    Write-Host "   无法检查服务: $_" -ForegroundColor Red
}
Write-Host ""

# 3. 测试端口连接
Write-Host "3. 测试端口 3306 连接..." -ForegroundColor Yellow
try {
    $result = Test-NetConnection -ComputerName 127.0.0.1 -Port 3306 -InformationLevel Quiet -WarningAction SilentlyContinue
    if ($result) {
        Write-Host "   ✓ 端口 3306 可连接" -ForegroundColor Green
    }
    else {
        Write-Host "   ✗ 端口 3306 无法连接" -ForegroundColor Red
        Write-Host "   说明: MySQL 服务未运行" -ForegroundColor Yellow
    }
}
catch {
    Write-Host "   ✗ 连接测试失败" -ForegroundColor Red
}
Write-Host ""

# 4. 尝试 Laravel 连接
Write-Host "4. 测试 Laravel 数据库连接..." -ForegroundColor Yellow
Write-Host "   正在运行 php artisan migrate..." -ForegroundColor Gray
try {
    $output = php artisan migrate 2>&1
    if ($LASTEXITCODE -eq 0) {
        Write-Host "   ✓ 数据库连接成功！" -ForegroundColor Green
    }
    else {
        Write-Host "   ✗ 数据库连接失败" -ForegroundColor Red
    }
}
catch {
    Write-Host "   ✗ 执行失败" -ForegroundColor Red
}
Write-Host ""

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "诊断完成" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan

